/*
 * *******************************************************************
 *   @项目名称: BHex Android
 *   @文件名称: CoinDialogFragment.java
 *   @Date: 18-11-29 下午4:05
 *   @Author: ppzhao
 *   @Description:
 *   @Copyright（C）: 2018 BlueHelix Inc.   All rights reserved.
 *   注意：本内容仅限于内部传阅，禁止外泄以及用于其他的商业目的.
 *  *******************************************************************
 */

package io.bhex.app.market.ui;

import android.annotation.SuppressLint;
import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.design.widget.TabLayout;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Pair;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;

import com.chad.library.adapter.base.BaseQuickAdapter;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import io.bhex.app.R;
import io.bhex.app.market.adapter.MarketListMultiAdapter;
import io.bhex.app.market.bean.FavoriteRecordBean;
import io.bhex.app.market.event.ItemClickStatusListener;
import io.bhex.app.skin.view.SkinTabLayout;
import io.bhex.app.utils.AnimalUtils;
import io.bhex.app.utils.CommonUtil;
import io.bhex.app.utils.KeyBoardUtil;
import io.bhex.app.utils.KlineUtils;
import io.bhex.app.utils.SkinColorUtil;
import io.bhex.app.view.TopBar;
import io.bhex.baselib.constant.AppData;
import io.bhex.baselib.network.Utils.CodeUtils;
import io.bhex.baselib.network.listener.SimpleResponseListener;
import io.bhex.baselib.utils.DebugLog;
import io.bhex.sdk.account.UserInfo;
import io.bhex.sdk.data_manager.SymbolDataManager;
import io.bhex.sdk.quote.QuoteApi;
import io.bhex.sdk.quote.bean.CoinPairBean;
import io.bhex.sdk.quote.bean.FavoriteListResponse;
import io.bhex.sdk.quote.bean.NewCoinPairListBean;
import io.bhex.sdk.quote.bean.QuoteTokensBean;
import io.bhex.sdk.quote.bean.TickerBean;
import io.bhex.sdk.quote.bean.TickerListBean;
import io.bhex.sdk.socket.NetWorkObserver;

/**
 * ================================================
 * 描   述：交易选择币对
 * ================================================
 */

@SuppressLint("ValidFragment")
public class CoinDialogFragment extends DialogFragment implements ViewPager.OnPageChangeListener, View.OnClickListener, ItemClickStatusListener {
    private DialogInterface.OnDismissListener mOnDismissListener;
    private String mSymbolId = "";
    private CoinPairBean mCoinPairBean;
    private Bitmap mBlurBg;
    private ImageView closeSearch;
    private EditText editSearch;
    private ViewPager viewPager;
    private RecyclerView recyclerView;
    private SkinTabLayout tab;
    private TopBar topBar;
    private RelativeLayout searchRela;
    private ArrayList<Pair<String, QuoteTokensBean.TokenItem>> items;
    private MarketAdapter marketAdapter;
    private String currentExchangeId;
    private MarketListMultiAdapter adapter;
    private RelativeLayout rootView;
    private View divider;
    private List<CoinPairBean> coinPairList;
    private RelativeLayout bottomRela;
    private boolean isTouching = false;
    private static final int TOUCH_DOWN_NOTIFY = 1; //触摸down
    private static final int TOUCH_UP_OR_CANCEL_NOTIFY = 2; //触摸up 或者cancel
    private List<CoinPairBean> mData;

    @SuppressLint("ValidFragment")
    public CoinDialogFragment(CoinPairBean coinPairBean, DialogInterface.OnDismissListener onDismissListener) {
        super();
        //mBlurBg = blurBg;
        mCoinPairBean = coinPairBean;
        if (mCoinPairBean != null) {
            mSymbolId = mCoinPairBean.getSymbolId();
        }
        mOnDismissListener = onDismissListener;
    }

    public CoinDialogFragment() {
        super();
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //这句代码的意思是让dialogFragment弹出时沾满全屏
//        setStyle(DialogFragment.STYLE_NORMAL, android.R.style.Theme_Holo_Light_DialogWhenLarge_NoActionBar);
        setStyle(DialogFragment.STYLE_NORMAL, R.style.popDialogStyle);
//        setStyle(DialogFragment.STYLE_NO_TITLE, android.R.style.Theme_Light);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
//        getDialog().setCanceledOnTouchOutside(false);
//        getDialog().requestWindowFeature(Window.FEATURE_NO_TITLE);//去掉Dialog标题
        View view = inflater.inflate(R.layout.pop_coinpair_layout, container, false);
        //让DialogFragment的背景为透明
        Window window = getDialog().getWindow();

        getDialog().getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        //window.setBackgroundDrawable(new BitmapDrawable(mBlurBg));
        WindowManager.LayoutParams wlp = window.getAttributes();
        wlp.gravity = Gravity.BOTTOM;
        wlp.width = WindowManager.LayoutParams.MATCH_PARENT;
        wlp.height = WindowManager.LayoutParams.MATCH_PARENT;
//      wlp.height = PixelUtils.getScreenHeight();
//      window.getDecorView().setPadding(0,0,0,0);
        window.setAttributes(wlp);
        initView(view);
        initEvent();
        return view;
    }

    //初始化view
    private void initView(View view) {
        rootView = view.findViewById(R.id.rootView);
        bottomRela = view.findViewById(R.id.bottomRela);
        closeSearch = view.findViewById(R.id.close_search);
        editSearch = view.findViewById(R.id.edit_search);
        editSearch.setHintTextColor(SkinColorUtil.getDark50(this.getActivity()));
        searchRela = view.findViewById(R.id.rela_search);

        viewPager = view.findViewById(R.id.clViewPager);
        recyclerView = view.findViewById(R.id.clRecyclerView);
        tab = view.findViewById(R.id.tabCoin);
        tab.setTabTextColors(SkinColorUtil.getDark(this.getActivity()), getResources().getColor(R.color.blue));
        divider = view.findViewById(R.id.divider);
        topBar = view.findViewById(R.id.topBar);
        topBar.setTitleRightDrawable(R.mipmap.icon_drawer);
        AnimalUtils.rotateyAnimRun(topBar.getTitleIcon(), 0.0f, 180.0f);
        if (mCoinPairBean != null) {
            topBar.setTitle(mCoinPairBean.getBaseTokenName() + "/" + mCoinPairBean.getQuoteTokenName());
        }

        getCoinPairList();
    }

    private void initEvent() {
        bottomRela.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                KeyBoardUtil.closeKeybord(editSearch, getActivity());
                closePop(false);
            }
        });
        topBar.setTitleOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                KeyBoardUtil.hideKeyboard(getActivity());
                closePop(false);
            }
        });
        closeSearch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                tab.setVisibility(View.VISIBLE);
                divider.setVisibility(View.VISIBLE);
                topBar.setVisibility(View.VISIBLE);
                searchRela.setVisibility(View.GONE);
                editSearch.setText("");
                filterList.clear();
                changePage(getCurrentTabId());

                AnimalUtils.alphaAnimRun(topBar, true ? 0.0f : 1.0f, true ? 1.0f : 0.0f);
//                AnimalUtils.scaleAnimRun(searchRela, false ? 0.0f : 1.0f, false ? 1.0f : 0.0f);
                KeyBoardUtil.closeKeybord(editSearch, getActivity());
            }
        });

        topBar.setRightImg(R.mipmap.icon_search);
        topBar.setRightOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                topBar.setVisibility(View.GONE);
                searchRela.setVisibility(View.VISIBLE);
                tab.setVisibility(View.GONE);
                divider.setVisibility(View.GONE);
                if (adapter != null) {
                    adapter.setNewData(null);
                }
                AnimalUtils.alphaAnimRun(topBar, false ? 0.0f : 1.0f, false ? 1.0f : 0.0f);
//                AnimalUtils.scaleAnimRun(searchRela, true ? 0.0f : 1.0f, true ? 1.0f : 0.0f);
                //KeyBoardUtil.openKeybord(editSearch, getActivity());

                editSearch.setFocusable(true);
                editSearch.setFocusableInTouchMode(true);
            }
        });
        editSearch.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (TextUtils.isEmpty(s)) {
                    editSearch.setTextAppearance(getActivity(), CommonUtil.isBlackMode() ? R.style.H4_Grey_No_Bold_night : R.style.H4_Grey_No_Bold);
                    editSearch.setHintTextColor(SkinColorUtil.getDark50(CoinDialogFragment.this.getActivity()));
                } else {
                    editSearch.setTextAppearance(getActivity(), CommonUtil.isBlackMode() ? R.style.H4_Dark_night : R.style.H4_Dark);
                    editSearch.setHintTextColor(SkinColorUtil.getDark50(CoinDialogFragment.this.getActivity()));
                }
                searchCoin(s.toString().trim());
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
    }

    @Override
    public void onCancel(DialogInterface dialog) {
        super.onCancel(dialog);
    }

    @Override
    public void onDismiss(DialogInterface dialog) {
        super.onDismiss(dialog);
        QuoteApi.UnSubTickers();
        if (mOnDismissListener != null) {
            mOnDismissListener.onDismiss(dialog);
        }
    }

    private ArrayList<CoinPairBean> filterList = new ArrayList<>();

    /**
     * 搜索币种
     *
     * @param searchContent
     */
    private void searchCoin(String searchContent) {
        if (adapter == null)
            return;
        if (TextUtils.isEmpty(searchContent)) {
            adapter.setNewData(null);
            return;
        }
        if (coinPairList != null) {
            filterList.clear();
            for (CoinPairBean coinPairBean : coinPairList) {
                if (isMatch(searchContent, coinPairBean)) {
                    filterList.add(coinPairBean);
                }

            }
            adapter.setNewData(filterList);
        }
    }

    private boolean isMatch(String searchContent, CoinPairBean coinPairBean) {
        String quoteTokenName = coinPairBean.getQuoteTokenName();
        String baseTokenName = coinPairBean.getBaseTokenName();
        if (!TextUtils.isEmpty(searchContent)) {
            searchContent = searchContent.toUpperCase();
        }
        if (!TextUtils.isEmpty(baseTokenName)) {
            baseTokenName = baseTokenName.toUpperCase();
            if (baseTokenName.contains(searchContent)) {
                return true;
            }
        }
        if (!TextUtils.isEmpty(quoteTokenName)) {
            quoteTokenName = quoteTokenName.toUpperCase();
            return quoteTokenName.contains(searchContent);
        }

        return false;
    }

    public void closePop(boolean isNeedCancelSub) {
        if (getDialog().isShowing()) {
            KeyBoardUtil.closeKeybord(editSearch, getActivity());
            dismiss();
        }
        /*if (isNeedCancelSub) {

            QuoteApi.UnSubTickers();
        }*/
    }

    /**
     * 市场fragment
     *
     * @param tabMap
     */
    private void initFragmentTab(LinkedHashMap<String, QuoteTokensBean.TokenItem> tabMap) {

        items = new ArrayList<>();

        for (String tabId : tabMap.keySet()) {
            QuoteTokensBean.TokenItem tokenItem = tabMap.get(tabId);

            String first = tokenItem.getTokenId().equals(AppData.KEY_FAVORITE) ? AppData.KEY_FAVORITE : tokenItem.getTabName();
            items.add(new Pair<String, QuoteTokensBean.TokenItem>(first, tokenItem));
//            items.add(new Pair<String, Fragment>(tokenItem.getTokenName(), new MarketListFragment()));
        }
        marketAdapter = new MarketAdapter(getChildFragmentManager());
        viewPager.setAdapter(marketAdapter);
        tab.setupWithViewPager(viewPager);
        tab.getTabAt(0).setText("");
        tab.getTabAt(0).setIcon(R.mipmap.icon_favorite_checked);
        tab.setTabMode(TabLayout.MODE_SCROLLABLE);
        tab.setTabGravity(TabLayout.GRAVITY_CENTER);
        CommonUtil.setUpIndicatorWidthByReflex2(tab, 15, 15);

        viewPager.addOnPageChangeListener(this);

        int currentPage = 0;
        if (items.size() > 1) {
            if (checkHasFavoriteSymbols()) {
                currentPage = 0;    //有自选，默认到自选列表（当前自选列表是tab第0页）
            }else{
                currentPage = 1;    //没有自选，默认到非自选列表
            }
            viewPager.setCurrentItem(currentPage);
        }
    }

    /**
     * 检查是否有自选币对
     * @return
     */
    private boolean checkHasFavoriteSymbols() {
        FavoriteRecordBean favoriteRecordBean = KlineUtils.getFavorite();
        if (favoriteRecordBean == null) {
            return false;
        }
        List<CoinPairBean> dataFavorite = favoriteRecordBean.getData();
        if (dataFavorite == null) {
            return false;
        }
        if (dataFavorite.size()>0) {
            return true;
        }
        return false;
    }

    public void showTabOfQuoteTokens(LinkedHashMap<String, QuoteTokensBean.TokenItem> tokens) {
        initFragmentTab(tokens);
    }

    /**
     * 默认返回自选
     *
     * @return
     */
    public String getCurrentTabId() {
        if (marketAdapter != null) {
            return marketAdapter.TokenID(viewPager.getCurrentItem());
        }
        return AppData.KEY_FAVORITE;
    }

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

    }

    @Override
    public void onPageSelected(int position) {
        String tabId;
        if (marketAdapter != null) {
            tabId = marketAdapter.TokenID(viewPager.getCurrentItem());
        } else {
            tabId = AppData.KEY_FAVORITE;
        }
        if (position == 0) {
            tab.getTabAt(0).setIcon(R.mipmap.icon_favorite_checked);
        } else {
            tab.getTabAt(0).setIcon(CommonUtil.isBlackMode() ? R.mipmap.icon_favorite_tab_night : R.mipmap.icon_favorite_tab);
        }
        changePage(tabId);
    }

    @Override
    public void onPageScrollStateChanged(int state) {

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
        }
    }

    private Handler mHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what){
                case TOUCH_DOWN_NOTIFY:
                    isTouching = false;
                    showMarket(mData);
                    break;
                case TOUCH_UP_OR_CANCEL_NOTIFY:
                    isTouching = false;
                    showMarket(mData);
                    break;
            }
        }
    };

    @Override
    public void onItemStatusListener(boolean isClick) {
        if (isClick) {
            isTouching = true;
            mHandler.sendEmptyMessageDelayed(TOUCH_DOWN_NOTIFY,1000);
        }else{
            mHandler.sendEmptyMessageDelayed(TOUCH_UP_OR_CANCEL_NOTIFY,200);
        }
    }

    private class MarketAdapter extends FragmentPagerAdapter {

        public MarketAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {
            return null;
        }

        @Override
        public int getCount() {
            return items.size();
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return items.get(position).first;
        }

        public String TokenID(int position) {
            String tokenId = "";
            if (items.get(position).second != null)
                tokenId = items.get(position).second.getTokenId();
            return tokenId;
        }

    }

    //创建tab 数据Map
    LinkedHashMap<String, QuoteTokensBean.TokenItem> tabMap = new LinkedHashMap<>();

    /**
     * 创建tab数据集
     *
     * @param response
     */
    private LinkedHashMap<String, QuoteTokensBean.TokenItem> createTabMap(List<QuoteTokensBean.TokenItem> response) {
        try {
            tabMap.clear();
            List<QuoteTokensBean.TokenItem> tabList = response;
            if (tabList != null) {
                //添加 默认第一个tab为自选
                QuoteTokensBean.TokenItem itemFavorite = new QuoteTokensBean.TokenItem();
                itemFavorite.setTokenId(AppData.KEY_FAVORITE);
                itemFavorite.setTabName(getActivity().getResources().getString(R.string.string_favorite));
                itemFavorite.setTokenName(getActivity().getResources().getString(R.string.string_favorite));
                itemFavorite.setTokenFullName(getResources().getString(R.string.string_favorite));
                tabList.add(0, itemFavorite);

                for (QuoteTokensBean.TokenItem tokenItem : tabList) {
                    DebugLog.e("MAP", tokenItem.getTokenId() + tokenItem.getTokenFullName());
                    tokenItem.setTabName(tokenItem.getTokenName());
                    tabMap.put(tokenItem.getTokenId(), tokenItem);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return tabMap;
    }

    /**
     * 获取币对列表
     */
    public void getCoinPairList() {
        SymbolDataManager.GetInstance().getNewCoinPairList(new SimpleResponseListener<NewCoinPairListBean>() {

            @Override
            public void onSuccess(NewCoinPairListBean response) {
                super.onSuccess(response);
                if (CodeUtils.isSuccess(response, true)) {
                    if (response.quoteToken != null && getActivity() != null) {

                        LinkedHashMap<String, QuoteTokensBean.TokenItem> tabMap = createTabMap(response.quoteToken);
                        showTabOfQuoteTokens(tabMap);

                        handQuoteTokenList(response.quoteToken);
                        getRealTimeData();
                    }

                }
            }

        });

    }


    /**
     * 拼接行情参数
     *
     * @return
     */
    private String getSymbolsListStr() {
        StringBuffer stringBuffer = new StringBuffer();
        for (String key : tabMap.keySet()) {
            if (!key.equals(AppData.KEY_FAVORITE)) {//刷出自选,因为其他的列表已经包括
                QuoteTokensBean.TokenItem tokenItem = tabMap.get(key);
                if (tokenItem != null) {
                    HashMap<String, CoinPairBean> coinPairMap = tokenItem.getCoinPairMap();
                    if (coinPairMap != null) {
                        if (!coinPairMap.isEmpty()) {
                            for (String keyOfCoin : coinPairMap.keySet()) {
                                CoinPairBean coinPairBean = coinPairMap.get(keyOfCoin);
                                if (coinPairBean != null) {
                                    String symbol = coinPairBean.getExchangeId() + "." + coinPairBean.getSymbolId();
                                    if (stringBuffer.toString().length() > 0) {
                                        stringBuffer.append("," + symbol);
                                    } else {
                                        stringBuffer.append(symbol);
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
        return stringBuffer.toString();
    }

    public void getRealTimeData() {
        String symbolsListStr = getSymbolsListStr();
        QuoteApi.SubTickers(symbolsListStr, new NetWorkObserver<TickerListBean>() {
            @Override
            public void onShowUI(TickerListBean response) {
                if (!isVisible() || response == null)
                    return;

                List<TickerBean> datas = response.getData();
                if (datas != null) {
                    for (TickerBean data : datas) {
                        handleSocketMarketList(data);
                    }
                }
            }

            @Override
            public void onError(String error) {
            }
        });

    }

    private void handleSocketMarketList(TickerBean tickerBean) {
        String currentTabId = getCurrentTabId();
        QuoteTokensBean.TokenItem currentTokenItem = tabMap.get(currentTabId);

        for (String key : tabMap.keySet()) {
            QuoteTokensBean.TokenItem tokenItem = tabMap.get(key);
            if (tokenItem != null) {
                HashMap<String, CoinPairBean> coinPairMap = tokenItem.getCoinPairMap();
                if (coinPairMap != null) {
                    for (String coinKey : coinPairMap.keySet()) {
                        CoinPairBean coinPairBean = coinPairMap.get(coinKey);
                        if (coinPairBean != null) {
                            String symbol = coinPairBean.getSymbolId();
                            String symbolTicker = tickerBean.getS();
                            if (symbol.equals(symbolTicker)) {
                                coinPairBean.setTicker(tickerBean);
                                if (currentTokenItem == tokenItem)
                                    notifyCoinPairListDataChange(tabMap);
                            }
                        }

                    }

                }

            }
        }
    }

    private void handQuoteTokenList(List<QuoteTokensBean.TokenItem> quoteTokenList) {
        //默认都取config接口symbol(全量列表)的实体列表
        HashMap<String, CoinPairBean> bbSymbolMap = SymbolDataManager.GetInstance().getBBSymbolMap();

        QuoteTokensBean.TokenItem favoriteToken = tabMap.get(AppData.KEY_FAVORITE);
        LinkedHashMap<String, CoinPairBean> favoriteMap = favoriteToken.getCoinPairMap();
        //登录添加网络同步的自选，
        if (UserInfo.isLogin()) {
            //如果登录了，先清空本地和内存中的自选
            if (favoriteMap != null) {
                favoriteMap.clear();
                KlineUtils.clearFavoriteRecord();
            }
            Map<String, FavoriteListResponse.FavoriteBean> loginFavoritesMap = SymbolDataManager.GetInstance().getFavoritesMap();
            for (String key : loginFavoritesMap.keySet()) {
                FavoriteListResponse.FavoriteBean favoriteBean = loginFavoritesMap.get(key);
                String favoriteSymbolId = favoriteBean.getSymbolId();
                CoinPairBean coinPairBean = bbSymbolMap.get(favoriteSymbolId);
                if (coinPairBean != null) {
                    favoriteMap.put(favoriteSymbolId,coinPairBean);
                    KlineUtils.saveFavorite(coinPairBean);
                }
            }
        }else{
            /***未登录，添加本地自选**/
            FavoriteRecordBean favoriteRecordBean = KlineUtils.getFavorite();
            List<CoinPairBean> localFavoriteList = favoriteRecordBean.getData();
            if (localFavoriteList != null) {
                if (favoriteToken != null) {
                    for (CoinPairBean coinPairBean : localFavoriteList) {
                        coinPairBean.setItemShowType(MarketListMultiAdapter.ITEM_TYPE_BB);
                        favoriteToken.getCoinPairMap().put(coinPairBean.getSymbolId(), coinPairBean);
                    }
                }
            }
        }

        for (QuoteTokensBean.TokenItem tokenItem : quoteTokenList) {
            LinkedHashMap<String, CoinPairBean> currentQuoteCoinPairMap = tokenItem.getCoinPairMap();
            List<CoinPairBean> quoteTokenSymbols = tokenItem.getQuoteTokenSymbols();
            if (quoteTokenSymbols != null) {
                for (CoinPairBean quoteTokenSymbol : quoteTokenSymbols) {
                    if (quoteTokenSymbol.isShowStatus()) {
                        String symbolId = quoteTokenSymbol.getSymbolId();
                        CoinPairBean coinPairBean = bbSymbolMap.get(symbolId);
                        currentQuoteCoinPairMap.put(symbolId,coinPairBean);
                    }

                }
            }
        }

        notifyCoinPairListDataChange(tabMap);
    }

//    /**
//     * APP首次打开提示交易界面使用的默认币对
//     * @param coinPairList
//     */
//    private void notifyTradeCoinPair(List<CoinPairBean> coinPairList) {
//        if (isSendDefaultCoinPair) {
//            return;
//        }
//        if (coinPairList.size() > 0) {
//            CoinPairBean coinPairBean = coinPairList.get(0);
//            coinPairBean.setNeedSwitchTradeTab(false);
//            EventBus.getDefault().postSticky(coinPairBean);
//            isSendDefaultCoinPair = true;
////            ToastUtils.showShort("HOME Post");
//        }
//
//    }

    /**
     * 提示币对数据更新
     *
     * @param tabMap
     */
    private void notifyCoinPairListDataChange(HashMap<String, QuoteTokensBean.TokenItem> tabMap) {
        String currentTabId = getCurrentTabId();
        QuoteTokensBean.TokenItem tokenItem = tabMap.get(currentTabId);
//        if (tokenItem != null) {
//            EventBus.getDefault().post(tokenItem);
//        } else {
//            DebugLog.e("MarketList tokenItem is null of " + currentTab);
//        }

        if (tokenItem != null) {
            HashMap<String, CoinPairBean> coinPairMap = tokenItem.getCoinPairMap();
            List<CoinPairBean> coinPairList = new ArrayList<>();
            for (String key : coinPairMap.keySet()) {
                CoinPairBean coinPairBean = coinPairMap.get(key);
                coinPairList.add(coinPairBean);
            }

            if (filterList != null && filterList.size() > 0)
                showMarket(filterList);
            else
                showMarket(coinPairList);
        }
    }

    private void showMarket(List<CoinPairBean> coinPairList) {
        mData = coinPairList;
        if (!isTouching) {  //如果处于点击操作时，暂时不更新UI
            if (adapter != null) {
                adapter.setNewData(coinPairList);
                return;
            }

            LayoutInflater layoutInflater = LayoutInflater.from(getActivity());
            View emptyView = layoutInflater.inflate(R.layout.empty_layout, rootView, false);
//        ViewGroup.LayoutParams layoutParams = emptyView.getLayoutParams();
//        layoutParams.height = PixelUtils.dp2px(getHeight());
//        emptyView.setLayoutParams(layoutParams);
            emptyView.findViewById(R.id.empty_txt).setOnClickListener(this);
            emptyView.findViewById(R.id.empty_img).setOnClickListener(this);

            adapter = new MarketListMultiAdapter(getActivity(),coinPairList,true,mSymbolId,this);
//            adapter.openLoadAnimation(BaseQuickAdapter.SCALEIN);
            adapter.isFirstOnly(false);
//            adapter.setOnLoadMoreListener(this);
            recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
            recyclerView.setItemAnimator(new DefaultItemAnimator());
            recyclerView.setAdapter(adapter);
            adapter.setEmptyView(emptyView);

            adapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
                @Override
                public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                    List<CoinPairBean> data = adapter.getData();
                    CoinPairBean itemModel = data.get(position);
                    //来自交易界面
                    itemModel.setBuyMode(true);
                    itemModel.setNeedSwitchTradeTab(true);
                    //IntentUtils.goTrade(mContext, itemModel);
                    EventBus.getDefault().postSticky(itemModel);
                    closePop(true);
                }
            });
            adapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
                @Override
                public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                    List<CoinPairBean> data = adapter.getData();
                    CoinPairBean itemModel = data.get(position);
                    //来自交易界面
                    itemModel.setBuyMode(true);
                    itemModel.setNeedSwitchTradeTab(true);
                    //IntentUtils.goTrade(mContext, itemModel);
                    EventBus.getDefault().postSticky(itemModel);
                    closePop(true);
                }
            });
        }
    }


    public void changePage(String tabId) {
        notifyCoinPairListDataChange(tabMap);
    }

}
